package com.atkid.boot.generator;

import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

@Component
public class ExcelGenerator {
	public XSSFWorkbook generate(String sheetName, String[] titles, String[][] values,int[] columnWidths) {
		// 第一步，创建一个XSSFWorkbook，对应一个Excel文件
		// 	wb = new HSSFWorkbook();
		XSSFWorkbook workbook = new XSSFWorkbook();

		// 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
		XSSFSheet sheet = workbook.createSheet(sheetName);

		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
		XSSFRow head = sheet.createRow(0);
		for (int i = 0; i < columnWidths.length; i++) {
			sheet.setColumnWidth(i,columnWidths[i]*256);
		}

		// 第四步，创建单元格，并设置值表头 设置表头居中
		XSSFCellStyle style = workbook.createCellStyle();
		style.setAlignment(HorizontalAlignment.CENTER);

		XSSFCellStyle headStyle = workbook.createCellStyle();
		headStyle.setAlignment(HorizontalAlignment.CENTER);
		XSSFFont headFont = workbook.createFont();
		headFont.setBold(true);
		headFont.setFontHeight(16);
		headStyle.setFont(headFont);

		//声明列对象
		XSSFCell cell = null;

		//创建标题
		for (int i = 0; i < titles.length; i++) {
			cell = head.createCell(i);
			cell.setCellValue(titles[i]);
			cell.setCellStyle(headStyle);
		}

		//创建内容
		XSSFRow row = null;
		for (int i = 0; i < values.length; i++) {
			row = sheet.createRow(i + 1);
			for (int j = 0; j < values[i].length; j++) {
				//将内容按顺序赋给对应的列对象
				XSSFCell valueCell = row.createCell(j);
				valueCell.setCellValue(values[i][j]);
				valueCell.setCellStyle(style);
			}
		}
		return workbook;
	}
}
